package cn.gdust.dao;

import cn.gdust.entity.Comment;
import cn.gdust.utils.DB;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {
    public List<Comment> findAll(String videoID) throws SQLException {
        List<Comment> list = new ArrayList<>();
        String sql = "SELECT * FROM  comments WHERE video_id=?";
        PreparedStatement stmt = null;
        try (Connection conn = DB.open()) {
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, videoID);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                Comment comment = new Comment();
                comment.setId(rs.getInt("id"));
                comment.setPost_id(rs.getInt("post_id"));
                comment.setUser_id(rs.getInt("user_id"));
                comment.setContent(rs.getString("content"));
                comment.setCreateTime(rs.getTimestamp("createTime"));
                comment.setUpdateTime(rs.getTimestamp("updateTime"));
                comment.setVideo_id(rs.getInt("video_id"));
                comment.setAvatar(rs.getString("avatar"));
                list.add(comment);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
        return list;
    }
    // 添加评论
    public int addComment(Comment comment) throws SQLException {
        String sql = "INSERT INTO comments(video_id, user_id, content, avatar, createtime) VALUE(?, ?, ?, ?, now())";
        PreparedStatement stmt = null;
        int result = 0;
        try (Connection conn = DB.open()) {
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, comment.getVideo_id());
            stmt.setInt(2, comment.getUser_id());
            stmt.setString(3, comment.getContent());
            stmt.setString(4, comment.getAvatar());
            result = stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
        // 返回改变的行数
        return result;
    }
}
